<?php
if( !APP_ROOT )
    return 'Direct Access Deny!';
    
use vendors\xunsearch\lib\XS;
use libraries\Benchmark;
use libraries\RQueue;
use libraries\Sms;
use libraries\RedLock;
use vendors\OSS\OssClient;
use enums\AppEnums;
use enums\EmailEnums;
use libraries\XEMail;

$di->set( 'bm', function(){
    $bm = new Benchmark();
    return $bm;
}, true);

// Registering a router
$di->set( 'router',function () {
    
    require_once APP_ROOT . 'config/router.php';
    return $router;
}, true );

// Registering unitTest
$di->set( 'utest', function () {
    return new \libraries\UnitTest();
}, true );


/**
 * apc cache
 */
$di->set( 'apcCache', function(){
    
    if( !extension_loaded( 'apc' ) )
    {
        return 'apc extension not loaded!<br>';
    }

    $frontCache = new \Phalcon\Cache\FrontEnd\Data( $this['cacheCfg']->apc->frontend->toArray() ); // cache two days
    $cache = new \Phalcon\Cache\Backend\Apc( $frontCache, $this['cacheCfg']->apc->backend->toArray() );

    return $cache;
}, true );

/**
 * memory 易失性 不能进行序列化 只能在一次请求中有效
 */
$di->set( 'memory', function (){
    
    $frontCache = new \Phalcon\Cache\FrontEnd\Data( $this['cacheCfg']->inmem->frontend->toArray() );
    $cache = new \Phalcon\Cache\Backend\Memory( $frontCache );

    return $cache;
}, true );



/**
 * redis cache
 */
$di->set( 'redisCache', function(){
    
    if( !extension_loaded( 'redis' ))
    {
        return 'redis extension not loaded!<br>';
    }
    
    $frontCache = new \Phalcon\Cache\FrontEnd\Data( $this['cacheCfg']->redisCache->frontend->toArray() );
    $cache = new \Phalcon\Cache\Backend\Redis( $frontCache, $this['cacheCfg']->redisCache->backend->toArray() );

    return $cache;
}, true );


/**
 * local native redis server
 */
$di->set( 'nredis', function()
{
	$redis = new \Redis();
	$redis->connect( $this['cacheCfg']->redisCache->backend->host, $this['cacheCfg']->redisCache->backend->port /*, 'password'*/ );
	$redis->auth( $this['cacheCfg']->redisCache->backend->auth );
	$redis->select( $this['cacheCfg']->redisCache->backend->index );
	return $redis;
}, true );

/**
 * native redis
 * 原生native使用phpredis扩展
 */
$di->set( 'aliRedis', function(){

    $redis = new \Redis();
    
    if( APP_MODE == AppEnums::APP_MODE_PRODUCTION )
    {
        $redis->connect( $this['cacheCfg']->aliRedisServer->host, 
            $this['cacheCfg']->aliRedisServer->port );
        $redis->auth( $this['cacheCfg']->aliRedisServer->auth );
    }
    else
    {
        $redis->connect( $this['cacheCfg']->redisCache->backend->host,
            $this['cacheCfg']->redisCache->backend->port );
        $redis->auth( $this['cacheCfg']->redisCache->backend->auth );
        
    }
    
    return $redis;
}, true );
    
    
$di->set( 'rqueue', function(){
    
    $redis = new \Redis();
    $redis->connect( $this['queueCfg']->server->host, $this['queueCfg']->server->port );
    $redis->auth( $this['queueCfg']->server->auth );
    
    $rq = new RQueue();
    $rq->setServer( $redis );
    
    return $rq;

}, true );


//-----------------------------------------
// email service
//-----------------------------------------
$di->set( 'email', function() {
    
	require_once APP_ROOT . 'vendors/swiftmailer/lib/swift_required.php';
	
 	if( EmailEnums::MODE_LOCAL == $this['emailCfg']->mode )
 	{
 		$transport = Swift_SendmailTransport::newInstance( $this['emailCfg']->{EmailEnums::MODE_LOCAL}->sendmail );
 	}
 	else 
 	{
 		$transport = Swift_SmtpTransport::newInstance( $this['emailCfg']->{ EmailEnums::MODE_ONLINE }->smtp_host, 
 			$this['emailCfg']->{ EmailEnums::MODE_ONLINE }->smtp_port )
 		->setUsername( $this['emailCfg']->{ EmailEnums::MODE_ONLINE }->smtp_user )
 		->setPassword( $this['emailCfg']->{ EmailEnums::MODE_ONLINE }->smtp_pass );
 	}
 	
 	$mailer = Swift_Mailer::newInstance( $transport );
 	
 	$mail = XEMail::getInstance( $mailer, $this );
 	
    return $mail;
    
}, true );

//-----------------------------------------
// sms service
//-----------------------------------------
$di->set( 'sms', function(){
    	
    $sms = Sms::getInstance( $this );
    return $sms;
});

//-----------------------------------------
// lock service
//-----------------------------------------
$di->set( 'redLock', function(){
    return new RedLock( $this[ 'nredis' ] );
} );

//-----------------------------------------
// xunsearch service
//-----------------------------------------

$arrXS = array( 
		array( 'name' => 'xs_museum', 'file' => 'museums' ),
		array( 'name' => 'xs_narrator', 'file' => 'narrators' ),
		array( 'name' => 'xs_exhibition', 'file' => 'exhibitions' ),
		array( 'name' => 'xs_event', 'file' => 'events' ),
		array( 'name' => 'xs_product', 'file' => 'products' ),
);

foreach( $arrXS as $xsApp ) 
{
	$di->set( $xsApp['name'], function() use ( $xsApp ) {
		if( file_exists( APP_ROOT . 'vendors/xunsearch/app/' . APP_MODE . '/' . $xsApp[ 'file' ] . '.ini' ) )
		{
			return new XS( APP_MODE . '_' . $xsApp[ 'file' ] );
		}
		else
		{
			return new XS( $xsApp[ 'file' ] );
		}
		
	}, true );
}


//-----------------------------------------
// oss service
//-----------------------------------------
$di->set( 'oss', function(){
    $cfg = require APP_ROOT . 'config/ueditor.php';

    $cur_oss = $cfg['oss_server'][ 'cur' ];
    $accessKeyId = $cfg['oss_server']['paths'][$cur_oss]['OSS_ACCESS_ID'];
    $accessKeySecret = $cfg['oss_server']['paths'][$cur_oss]['OSS_ACCESS_KEY'];
    $endpoint = $cfg['oss_server']['paths'][$cur_oss]['OSS_ENDPOINT'];
    try{
        return new OssClient( $accessKeyId, $accessKeySecret, $endpoint );
    }
    catch( \Exception $e )
    {
        var_dump( $e );
    }
});



$di->set( 'modelsMetadata',function(){ 
    
	$metaData = new \Phalcon\Mvc\Model\MetaData\Memory( array(
		'lifetime' => 1440,
	    'prefix' => 'metadata_'
	));
	return $metaData;
}, true );


$di->set( 'bizLog', function(){
	
	if( !file_exists( $this['logCfg']->log->bizLogPath ))
	{
		$logFile = fopen( $this['logCfg']->log->bizLogPath, 'a' );
		
		if( false !== $logFile )
		{
			fclose( $logFile );
		}
		else
		{//error
			
		}	
	}
	
    $logger = new Phalcon\Logger\Adapter\File( $this['logCfg']->log->bizLogPath );
    return $logger;
    
}, true );

$di->set( 'errLog', function(){
	
	if( !file_exists( $this['logCfg']->log->errLogPath ))
	{
		$logFile = fopen( $this['logCfg']->log->errLogPath, 'a'  );
	
		if( false !== $logFile )
		{
			fclose( $logFile );
		}
		else
		{//error
				
		}
	}
	
    $logger = new Phalcon\Logger\Adapter\File( $this['logCfg']->log->errLogPath );
    return $logger;
}, true );


$di->set( 'debugLog', function(){
	
	if( !file_exists( $this['logCfg']->log->debugLogPath ))
	{
		$logFile = fopen( $this['logCfg']->log->debugLogPath, 'a'  );
	
		if( false !== $logFile )
		{
			fclose( $logFile );
		}
		else
		{//error
				
		}
	}
	$logger = new Phalcon\Logger\Adapter\File( $this['logCfg']->log->debugLogPath );
	return $logger;
}, true );